package com.lizhi.parse;

import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.alibaba.fastjson.JSON;
import com.lizhi.model.BookModel;
import com.lizhi.model.model2.ChapterModel;
import com.lizhi.util.Util;

public class ParseBookDetail extends Thread {
	private BookModel mBookModel;
	private String mHref;

	public ParseBookDetail(BookModel bookModel, String href) {
		mBookModel = bookModel;
		mHref = href;
	}

	@Override
	public void run() {

		while (true) {
			try {
				Document document = Util.getDocument(mHref);
				Elements desElements = document.getElementsByClass("des");
				Elements chapterElements = document.getElementsByClass("articleTitle");

				mBookModel.brief = desElements.text();

				for (int i = 0; i < chapterElements.size(); i++) {
					Element element = chapterElements.get(i);
					String href = element.attr("href");
					String name = element.text();
					ChapterModel chapterModel = new ChapterModel();
					chapterModel.name = name;
					chapterModel.url = href.replace(".html", ".json");
					String[] temps = href.split("/");
					String id = temps[temps.length - 1].replace(".html", "");
					chapterModel.id = id;
					chapterModel.bid = mBookModel.id;
					if(i>2){
						chapterModel.points=String.valueOf(5);
					}else {
						chapterModel.points="0";
					}
					mBookModel.chapterModels.add(chapterModel);
					String next = null;
					if (i < (chapterElements.size() - 1)) {
						next = chapterElements.get((i + 1)).attr("href").replace(".html", ".json");
					}
					System.out.println("parse chapter "+chapterModel.name+" finish!");
					sleep(2000);
					Util.execute(new ParseChapter(chapterModel, href, next));
				}

				System.out.println("upload book:"+mBookModel.name);
				Util.upload(Util.getBookURL()+"books.json", JSON.toJSONString(mBookModel));
				break;
			} catch (Exception e) {
				Util.saveFile(mBookModel.name+".txt", mHref);
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e1) {
					e1.printStackTrace();
				}
			}

		}
	}

	public static void main(String[] args) {

		BookModel bookModel=new BookModel();
		bookModel.id="123242";
		bookModel.name="sdfsdf";
		new ParseBookDetail(new BookModel(), "http://www.sbkk8.cn/lizhishu/kaozijiquchenggong/").start();
	}
}
